package generator.util;

import lombok.Data;
import lombok.experimental.Accessors;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * <p>
 *
 * </p>
 *
 * @author angel.bin@aliyun.com
 * @since 2020-10-05 13:34
 */
public class JdbcUtils {

    private static ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();

    private static JdbcConfig jdbcConfig;

    static {
        try (InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties")) {
            Properties properties = new Properties();
            properties.load(in);
            jdbcConfig = new JdbcConfig()
                    .setDatabase(properties.getProperty("database"))
                    .setPassword(properties.getProperty("password"))
                    .setPort(Integer.parseInt(properties.getProperty("port")))
                    .setHost(properties.getProperty("host"))
                    .setUsername(properties.getProperty("username"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection connection = JdbcUtils.connectionThreadLocal.get();
        if (connection == null) {
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                connection = DriverManager.getConnection("jdbc:mysql://" + jdbcConfig.getHost() + ":" + jdbcConfig.getPort() + "/" + jdbcConfig.getDatabase(),
                        jdbcConfig.getUsername(),
                        jdbcConfig.getPassword());
                JdbcUtils.connectionThreadLocal.set(connection);
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    public static void close() {
        if (connectionThreadLocal != null) {
            Connection connection = connectionThreadLocal.get();
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            connectionThreadLocal.remove();
        }
    }

    @Data
    @Accessors(chain = true)
    public static class JdbcConfig {
        private String username;

        private String password;

        private Integer port;

        private String host;

        private String database;
    }
}
